import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const useDataFieldStore = defineStore('dataField', () => {
  const dataFieldList = ref([]);
  const dataFieldMap = ref([]);
  const loading = ref(false);

  const setByModelId = (modelId, list) => {
    if (!list) return;
    dataFieldMap.value[modelId] = list;
    (list || []).forEach(item => {
      if (!dataFieldList.value[item.id]) {
        dataFieldList.value[item.id] = item;
      }
    });
  };

  const getByModelId = async(modelId) => {
    if (!modelId) return [];
    if (dataFieldMap.value[modelId] && dataFieldMap.value[modelId].length > 0) {
      return dataFieldMap.value[modelId] || [];
    }

    if (loading.value) {
      await sleep(100);
      return await getByModelId(modelId);
    }

    loading.value = true;
    try {
      const res = await api.post('/business/data-field/list/' + modelId);
      loading.value = false;
      setByModelId(modelId, res.data);
      return dataFieldMap.value[modelId] || [];
    } finally {
      loading.value = false;
    }
  };

  const setById = (id, data) => {
    if (!data) return;
    dataFieldList.value[id] = data;
  };

  const getById = async(id) => {
    if (dataFieldList.value[id]) {
      return dataFieldList.value[id] || {};
    }

    if (loading.value) {
      await sleep(100);
      return await getById(id);
    }

    loading.value = true;
    try {
      const res = await api.post('/business/data-field/' + id);
      loading.value = false;
      setById(id, res.data);
      return dataFieldList.value[id] || {};
    } finally {
      loading.value = false;
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  const clearData = () => {
    dataFieldList.value = [];
    dataFieldMap.value = [];
  };

  return { getById, getByModelId, clearData };
});
